package framwork

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"time"
)


type LoggerMiddle struct {
	procName string
	config gin.LoggerConfig
}

func (l *LoggerMiddle)Init(){
	l.config = gin.LoggerConfig{}
	l.SetFormat()
	l.SetLoggerPath()
	l.SetSkipPath()
}

func (l *LoggerMiddle)GetLogger()gin.HandlerFunc{
	// 禁用色彩
	gin.DisableConsoleColor()

	// 获取自带的logger
	ginLogger := gin.LoggerWithConfig(l.config)

	return ginLogger
}

func (l *LoggerMiddle)SetFormat(){
	formatter := func (param gin.LogFormatterParams) string{
		// your custom format
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}
	l.config.Formatter = formatter
}

func (l *LoggerMiddle)SetLoggerPath(){
	f, _ := os.OpenFile(fmt.Sprintf("./%v.log", l.procName), os.O_CREATE | os.O_WRONLY, 0666)
	l.config.Output = io.MultiWriter(f)
}


func (l *LoggerMiddle)SetSkipPath(){
	l.config.SkipPaths = nil
}
